package vip.liux.backend.infrastructure.config;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.core.ContextAwareScheduledThreadPoolExecutor;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

// 标注为配置类
@Configuration(proxyBeanMethods = false)
public class Resilience4Configuration {

    // 定义默认的 Resilience4J CircuitBreaker 配置
    @Bean
    public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> {
            // 配置默认的 CircuitBreaker
            factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                    // 配置超时限制器，超时时间为 4 秒
                    .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build())
                    // 使用默认的断路器配置
                    .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
                    .build());
            // 创建一个上下文感知的线程池执行器
            ContextAwareScheduledThreadPoolExecutor executor = ContextAwareScheduledThreadPoolExecutor
                    .newScheduledThreadPool() // 创建线程池
                    .corePoolSize(5) // 设置核心线程数为 5
                    .build();
            // 配置线程池执行器
            factory.configureExecutorService(executor);
        };
    }

    // 定义针对 "rest" 的 Resilience4J CircuitBreaker 配置
    @Bean
    public Customizer<Resilience4JCircuitBreakerFactory> restCustomizer() {
        return factory -> factory
                // 配置 "rest" 的断路器和超时限制器
                .configure(builder -> builder.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()) // 使用默认断路器配置
                        .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build()), "rest"); // 超时时间为 2 秒
    }
}